<template>
  <div id="questionsView">
    <nav class="py-4 overflow-x-auto whitespace-nowrap">
      <div class="flex gap-3">
        <button
          v-for="(tag, index) in tags"
          :key="index"
          @click="handleTagClick(tag)"
          :class="[
            'px-4 py-2 rounded-full transition-all duration-300 flex items-center gap-2 !rounded-button whitespace-nowrap',
            activeTag === tag.value
              ? 'bg-gray-900 text-white'
              : 'bg-gray-100 text-gray-700 hover:bg-gray-200',
          ]"
        >
          <el-icon class="text-lg">
            <component :is="tag.icon" />
          </el-icon>
          {{ tag.label }}
        </button>
      </div>
    </nav>
    <a-form :model="searchParams" layout="inline">
      <a-form-item field="title" label="名称" style="min-width: 240px">
        <a-input v-model="searchParams.title" placeholder="请输入名称" />
      </a-form-item>
      <a-form-item field="tags" label="标签" style="min-width: 240px">
        <a-input-tag v-model="searchParams.tags" placeholder="请输入标签" />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" @click="doSubmit">提交</a-button>
      </a-form-item>
    </a-form>
    <a-divider size="0" />
    <a-table
      :ref="tableRef"
      style="width: 1000px"
      :columns="columns"
      :data="dataList"
      :pagination="{
        showTotal: true,
        pageSize: searchParams.pageSize,
        current: searchParams.current,
        total,
      }"
      @page-change="onPageChange"
    >
      <template #tags="{ record }">
        <a-space wrap>
          <a-tag v-for="(tag, index) of record.tags" :key="index" color="green"
            >{{ tag }}
          </a-tag>
        </a-space>
      </template>
      <template #acceptedRate="{ record }">
        {{
          `${
            record.submitNum
              ? ((record.acceptedNum / record.submitNum) * 100).toFixed(2)
              : "0"
          } % (${record.acceptedNum}/${record.submitNum})`
        }}
      </template>
      <template #hardRant="{ record }">
        <a-tag v-if="record.hardRant === 'S'"> 简单</a-tag>
        <a-tag v-else-if="record.hardRant === 'M'" color="blue"> 中等</a-tag>
        <a-tag v-else-if="record.hardRant === 'L'" color="red"> 困难</a-tag>
      </template>
      <template #createTime="{ record }">
        {{ moment(record.createTime).format("YYYY-MM-DD") }}
      </template>
      <template #optional="{ record }">
        <a-space>
          <a-button type="primary" @click="toQuestionPage(record)">
            做题
          </a-button>
        </a-space>
      </template>
    </a-table>
    <RankList
      style="
        position: fixed;
        top: 120px; /* 距离顶部 20px */
        right: 20px; /* 距离右侧 20px */
        z-index: 9999;
      "
    />
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, watchEffect } from "vue";
import {
  Page_Question_,
  Question,
  QuestionControllerService,
  QuestionQueryRequest,
} from "../../../xiongoj_backendapi";
import message from "@arco-design/web-vue/es/message";
import { useRouter } from "vue-router";
import moment from "moment";
import RankList from "@/components/RankList.vue";
import { TagsControllerService } from "../../../backendapi";
const tableRef = ref();

const dataList = ref([]);
const total = ref(0);
const searchParams = ref<QuestionQueryRequest>({
  title: "",
  tags: [],
  pageSize: 8,
  current: 1,
});

const loadData = async () => {
  const res = await QuestionControllerService.listQuestionVoByPageUsingPost(
    searchParams.value
  );
  if (res.code === 0) {
    dataList.value = res.data.records;
    total.value = res.data.total;
  } else {
    message.error("加载失败，" + res.message);
  }
};

/**
 * 监听 searchParams 变量，改变时触发页面的重新加载
 */
watchEffect(() => {
  loadData();
});

/**
 * 页面加载时，请求数据
 */
onMounted(() => {
  loadData();
  fetchTags();
});

const columns = [
  {
    title: "题号",
    dataIndex: "id",
  },
  {
    title: "题目名称",
    dataIndex: "title",
  },
  {
    title: "标签",
    slotName: "tags",
  },
  {
    title: "题目难度",
    slotName: "hardRant",
  },
  {
    title: "通过率",
    slotName: "acceptedRate",
  },
  {
    title: "创建时间",
    slotName: "createTime",
  },
  {
    slotName: "optional",
  },
];
const onPageChange = (page: number) => {
  searchParams.value = {
    ...searchParams.value,
    current: page,
  };
};

const router = useRouter();

/**
 * 跳转到做题页面
 * @param question
 */
const toQuestionPage = (question: Question) => {
  router.push({
    path: `/view/question/${question.id}`,
  });
};

/**
 * 确认搜索，重新加载数据
 */
const doSubmit = () => {
  // 这里需要重置搜索页号
  searchParams.value = {
    ...searchParams.value,
    current: 1,
  };
};
// --------------------------------------------------搜索标签-------------------------------------------
import {
  List,
  DataLine,
  Share,
  ElementPlus,
  DataAnalysis,
  Reading,
  PictureRounded,
  MagicStick,
} from "@element-plus/icons-vue";
interface Tag {
  label: string;
  value: string;
  icon: any;
}
import { ElMessage } from "element-plus";
const tags = ref<Tag[]>([{ label: "全部题目", value: "all", icon: List }]);
const iconList = [
  DataLine,
  Share,
  ElementPlus,
  DataAnalysis,
  Reading,
  PictureRounded,
  MagicStick,
];

const fetchTags = async () => {
  try {
    const response = await TagsControllerService.getAllTagListUsingGet();
    if (response.code === 0) {
      const tagNames = response.data;
      tagNames.forEach((tagName: string, index: number) => {
        const icon = iconList[index] || null; // 如果图标数量不足，使用 null
        tags.value.push({ label: tagName, value: tagName, icon });
      });
    } else {
      ElMessage.error("获取标签列表失败: " + response.message);
    }
  } catch (error) {
    ElMessage.error("获取标签列表失败，请稍后重试");
  }
};
const activeTag = ref("all");
const handleTagClick = (tag: Tag) => {
  activeTag.value = tag.value;
  if (tag.label === "全部题目") {
    searchParams.value.tags?.pop();
    loadData();
    return;
  }
  searchParams.value.tags?.pop();
  searchParams.value.tags?.push(tag.label);
  loadData();
};
</script>

<style scoped>
#questionsView {
  max-width: 1280px;
  margin: 0 auto;
}
</style>
